<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Echart } from '@/components/Echart'
import { Table, TableColumn } from '@/components/Table'
import { ElDatePicker, ElRadioGroup, ElRadio } from 'element-plus'

import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ref, reactive, unref, computed } from 'vue'
import { getTakuNetworksApi, getTakuHoursListApi } from '@/api/dashboard/analysis'
import { useI18n } from '@/hooks/web/useI18n'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const { t } = useI18n()

const series = ref<any>([])
const legendData = ref<any>([])
const radio = ref()
const lineOptionsData = computed<any>(() => {
  return {
    xAxis: {
      data: [
        '0点',
        '1点',
        '2点',
        '3点',
        '4点',
        '5点',
        '6点',
        '7点',
        '8点',
        '9点',
        '10点',
        '11点',
        '12点',
        '13点',
        '14点',
        '15点',
        '16点',
        '17点',
        '18点',
        '19点',
        '20点',
        '21点',
        '22点',
        '23点'
      ],
      boundaryGap: false,
      axisTick: {
        show: true
      }
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 20,
      top: 80,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    legend: {
      data: legendData.value,
      type: 'scroll',
      orient: 'horizontal',
      top: 50
    },

    series: series.value
  }
})

// Search
const { searchRegister, searchMethods } = useSearch()
const { getFormData: getSearchFormData } = searchMethods

//formSchema
const AdvertisingOptions = ref()
const getTakuNetworks = async () => {
  const { data } = await getTakuNetworksApi()
  AdvertisingOptions.value = data.map((v) => {
    return {
      label: v.network_name,
      value: v.network_id
    }
  })
}
getTakuNetworks()

const disableCache = (time: any) => {
  const today = new Date()
  const october = new Date()
  october.setDate(october.getDate() - 7)
  return time.getTime() > today.getTime() || time.getTime() < october.getTime()
}
const schema = computed<any[]>(() => [
  {
    field: 'time',
    label: '日期筛选',
    formItemProps: {
      slots: {
        default: (formData) => {
          const times = computed({
            get: () => {
              if (formData.startDate && formData.endDate) {
                return [formData.startDate, formData.endDate]
              } else {
                return []
              }
            },
            set: (times) => {
              if (times) {
                formData.startDate = times[0]
                formData.endDate = times[1]
              } else {
                formData.startDate = undefined
                formData.endDate = undefined
              }
            }
          })
          return (
            <ElDatePicker
              v-model={times.value}
              type="daterange"
              valueFormat="YYYYMMDD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择日期范围"
              disabledDate={disableCache}
            />
          )
        }
      }
    }
  },
  {
    field: 'advertising',
    label: '广告平台',
    component: 'Select',
    componentProps: {
      options: AdvertisingOptions.value
    }
  }
  // {
  //   field: 'guanggao',
  //   label: '广告类型',
  //   component: 'Select',
  //   componentProps: {
  //     options: [
  //       {
  //         label: '全部',
  //         value: 'all'
  //       },
  //       {
  //         label: '百度',
  //         value: 'baidu'
  //       },
  //       {
  //         label: '搜狗',
  //         value: 'sogou'
  //       },
  //       {
  //         label: '360',
  //         value: '360'
  //       }
  //     ]
  //   }
  // },
  // {
  //   field: 'phone',
  //   label: '手机系统',
  //   component: 'Select',
  //   componentProps: {
  //     options: [
  //       {
  //         label: '全部',
  //         value: 'all'
  //       },
  //       {
  //         label: '百度',
  //         value: 'baidu'
  //       },
  //       {
  //         label: '搜狗',
  //         value: 'sogou'
  //       },
  //       {
  //         label: '360',
  //         value: '360'
  //       }
  //     ]
  //   }
  // }
])
//Table
const statementData = ref()
const { tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const searchFormData = await getSearchFormData()
    const { data } = await getTakuHoursListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      appIds: userStore.getAppId,
      ...searchFormData
    })
    statementData.value = data.statementData
    radio.value = data.statementData[0].field
    handleChange(data.statementData[0])
    return {
      list: data.data,
      total: data.count
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
enum HOUR {
  '00:00-00:59',
  '01:00-01:59',
  '02:00-02:59',
  '03:00-03:59',
  '04:00-04:59',
  '05:00-05:59',
  '06:00-06:59',
  '07:00-07:59',
  '08:00-08:59',
  '09:00-09:59',
  '10:00-10:59',
  '11:00-11:59',
  '12:00-12:59',
  '13:00-13:59',
  '14:00-14:59',
  '15:00-15:59',
  '16:00-16:59',
  '17:00-17:59',
  '18:00-18:59',
  '19:00-19:59',
  '20:00-20:59',
  '21:00-21:59',
  '22:00-22:59',
  '23:00-23:59'
}

const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'date',
    label: '日期'
  },
  {
    field: 'hour',
    label: '小时',
    slots: {
      default: ({ row }) => {
        return <span>{HOUR[row.hour]}</span>
      }
    }
  },
  {
    field: 'estimated_revenue',
    label: '预估收益',
    slots: {
      default: ({ row }) => {
        return <span>￥{row.estimated_revenue.toFixed(2)}</span>
      }
    }
  },
  {
    field: 'estimated_revenue_ecpm',
    label: '预估eCPM',
    slots: {
      default: ({ row }) => {
        return <span>￥{row.estimated_revenue_ecpm.toFixed(2)}</span>
      }
    }
  },
  {
    field: 'loads',
    label: '流量请求'
  },
  {
    field: 'load_fill_rate',
    label: '流量填充率',
    slots: {
      default: ({ row }) => {
        return <span>{(row.load_fill_rate * 100).toFixed(2)}%</span>
      }
    }
  },
  {
    field: 'request',
    label: '广告源请求'
  },
  {
    field: 'request_fill_rate',
    label: '广告源填充率',
    slots: {
      default: ({ row }) => {
        return <span>{(row.request_fill_rate * 100).toFixed(2)}%</span>
      }
    }
  },
  {
    field: 'impression',
    label: '展示'
  },
  {
    field: 'impression_rate',
    label: '展示率',
    slots: {
      default: ({ row }) => {
        return <span>{(row.impression_rate * 100).toFixed(2)}%</span>
      }
    }
  },
  {
    field: 'click',
    label: '点击'
  },
  {
    field: 'click_rate',
    label: '点击率',
    slots: {
      default: ({ row }) => {
        return <span>{(row.click_rate * 100).toFixed(2)}%</span>
      }
    }
  }
])

const handleChange = (res) => {
  series.value = []
  const keys = Object.keys(res.data)
  const values = Object.values(res.data)
  keys.forEach((item, index) => {
    series.value.push({
      name: item,
      type: 'line',
      data: values[index],
      smooth: true,
      itemStyle: {},
      animationDuration: 2800,
      animationEasing: 'quadraticOut'
    })
    legendData.value.push(item)
  })

  // console.log(series.value)
}
</script>

<template>
  <ContentWrap title="广告时段统计">
    <Search
      :schema="schema"
      :model="{
        startDate: dayjs().format('YYYYMMDD'),
        endDate: dayjs().format('YYYYMMDD')
      }"
      @search="getList"
      @reset="getList"
      @register="searchRegister"
    />
    <div class="flex">
      <div class="w-[80%]">
        <Echart :options="lineOptionsData" :height="350" />
      </div>
      <div class="ml-30px">
        <div
          class="w-[200px] h-[310px] max-h-[310px] border-1 border-solid border-[#dddfe6] overflow-scroll"
        >
          <div
            class="h-[40px] bg-#f5f7fa px-25px leading-40px border-b-1 text-14px"
            style="border-bottom: 1px solid #ccc"
            >指标</div
          >
          <ElRadioGroup v-model="radio" style="width: 100%">
            <ElRadio
              :value="item.field"
              v-for="item in statementData"
              :key="item.field"
              style="
                width: 100%;
                padding: 20px;
                border-bottom: 1px solid #dddfe6;
                font-size: 12px;
                margin-right: 0;
              "
              @change="handleChange(item)"
              >{{ item.name }}</ElRadio
            >
          </ElRadioGroup>
        </div>
      </div>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      :pagination="{
        total: total
      }"
    />
  </ContentWrap>
</template>
